package com.stylefeng.guns.modular.yjya.controller;

import cn.afterturn.easypoi.entity.vo.TemplateWordConstants;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.common.exception.BizExceptionEnum;
import com.stylefeng.guns.common.exception.BussinessException;
import com.stylefeng.guns.common.persistence.dao.AlarmMapper;
import com.stylefeng.guns.common.persistence.dao.RoadnetMapper;
import com.stylefeng.guns.common.persistence.dao.UserMapper;
import com.stylefeng.guns.common.persistence.model.*;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.shiro.ShiroKit;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.modular.yjya.service.IAccidentService;
import com.stylefeng.guns.modular.yjya.transfer.DisposeReport;
import com.stylefeng.guns.modular.yjya.transfer.Principal;
import com.stylefeng.guns.modular.yjya.warpper.AccidentWarpper;
import com.stylefeng.guns.modular.yjya.warpper.AlarmWrapper;
import com.stylefeng.guns.modular.yjya.warpper.CounterplanTemplateWarpper;
import com.stylefeng.guns.modular.yjya.warpper.CounterplanWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 事故实例控制器
 *
 * @author xuziyang
 * @Date 2018-01-22 19:37:07
 */
@Controller
@RequestMapping("/accident")
public class AccidentController extends BaseController {

    private String PREFIX = "/yjya/accident/";


    @Autowired
    private IAccidentService accidentService;

    @Autowired
    private AlarmMapper alarmMapper;

    @Autowired
    private RoadnetMapper roadnetMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 跳转到事故实例首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "accident.html";
    }

    /**
     * 添加事故实例
     */
    @RequestMapping("/accident_addaccident")
    public String accidentAddaccident(){
        return PREFIX + "accident_addaccident.html";
    }

    /**
     * 接警
     */
    @RequestMapping("/accident_add")
    public String accidentAdd(Model model) {
        //获取当前系统用户id
        Integer userId = ShiroKit.getUser().getId();
        //查询当前用户是否有正在应急处置的事故
        Alarm alarm = alarmMapper.selectByUserId(userId);
        if(alarm!=null){
            Map<String, Object> templateMap = BeanKit.beanToMap(alarm);
            model.addAttribute("item", new AlarmWrapper(templateMap).warp());
        }
        else{
            Map<String,Object> map= new HashMap<>();
            model.addAttribute("item", new AlarmWrapper(map).warp());
        }
        model.addAttribute("currentIndex",0);
        return PREFIX + "accident_add1.html";
    }

    /**
     * 跳转到处警
     */
    @RequestMapping("/accident_add_step_two")
    public String accidentAddStepTwo(Model model) {

        //获取当前系统用户id
        Integer userId = ShiroKit.getUser().getId();
        //查询当前用户是否有正在应急处置的事故
        Alarm alarm = alarmMapper.selectByUserId(userId);
        if(alarm!=null){
            Map<String, Object> templateMap = BeanKit.beanToMap(alarm);
            model.addAttribute("item", new AlarmWrapper(templateMap).warp());
        }
        else{
            Map<String,Object> map= new HashMap<>();
            model.addAttribute("item", new AlarmWrapper(map).warp());
        }
        model.addAttribute("currentIndex",1);
        return PREFIX + "accident_add1.html";
    }

    /**
     * 跳转到编制处置流程
     */
    @RequestMapping("/accident_add_step_three")
    public String accidentAddStepThree(Model model) {
        //获取当前系统用户id
        Integer userId = ShiroKit.getUser().getId();
        //查询当前用户是否有正在应急处置的事故
        Alarm alarm = alarmMapper.selectByUserId(userId);
        if(alarm!=null){
            Map<String, Object> templateMap = BeanKit.beanToMap(alarm);
            model.addAttribute("item", new AlarmWrapper(templateMap).warp());
        }
        else{
            Map<String,Object> map= new HashMap<>();
            model.addAttribute("item", new AlarmWrapper(map).warp());
        }
        model.addAttribute("currentIndex",2);
        return PREFIX + "accident_add1.html";
    }

    /**
     * 跳转到处置阶段
     */
    @RequestMapping("/accident_add_step_four")
    public String accidentAddStepFour(Model model) {
        //获取当前系统用户id
        Integer userId = ShiroKit.getUser().getId();
        //查询当前用户是否有正在应急处置的事故
        Alarm alarm = alarmMapper.selectByUserId(userId);
        if(alarm!=null){
            Map<String, Object> templateMap = BeanKit.beanToMap(alarm);
            model.addAttribute("item", new AlarmWrapper(templateMap).warp());
            model.addAttribute("processJson",alarm.getProcessJson());
        }
        else{
            Map<String,Object> map= new HashMap<>();
            model.addAttribute("item", new AlarmWrapper(map).warp());
        }
        model.addAttribute("currentIndex",3);
        return PREFIX + "accident_add1.html";
    }

    /**
     * 跳转到修改事故实例
     */
    @RequestMapping("/accident_update/{accidentId}")
    public String accidentUpdate(@PathVariable Integer accidentId, Model model) {
        Accident accident = accidentService.selectById(accidentId);
        Wrapper wrapper = new EntityWrapper<Accident>();
        wrapper.eq("id", accidentId);
        Map<String,Object> map = accidentService.selectMap(wrapper);
        model.addAttribute("item",new AccidentWarpper(map).warp());
        LogObjectHolder.me().set(accident);
        return PREFIX + "accident_edit.html";
    }

    @RequestMapping("/addProcess")
    @ResponseBody
    public Object addProcess(@RequestParam("id") Integer id,@RequestParam("process") String process) {
        Accident ac = new Accident();
        ac.setId(id);
        ac.setProcess(process);
        accidentService.updateById(ac);
        return super.SUCCESS_TIP;
    }

    @RequestMapping("process_execute")
    public String processExecute() {
        return PREFIX + "process_execute.html";
    }

    @RequestMapping("/getProcess")
    @ResponseBody
    public String getProcess(@RequestParam("id") Integer id) {
        Accident ac = accidentService.selectById(id);
        if (ac == null) {
             throw new BussinessException(BizExceptionEnum.REQUEST_NULL);
        }
        return ac.getProcess();
    }

    /**
     * 获取事故实例列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        List<Map<String,Object>> list = accidentService.selectMaps(null);
        return new AccidentWarpper(list).warp();
    }

    /**
     * 选择某条历史案例
     */
    @RequestMapping(value = "/select")
    @ResponseBody
    public Object select(@RequestParam Integer accidentId) {
        Accident accident = accidentService.selectById(accidentId);
        return accident;
    }

    /**
     * 选择某条历史案例
     */
    @RequestMapping(value = "/selectdisposaljson")
    @ResponseBody
    public Object selectdisposaljson(@RequestParam Integer accidentId) {
        Accident accident = accidentService.selectById(accidentId);
        return accident;
    }

    /**
     * 手动新增事故实例
     */
    @RequestMapping(value = "/addAccident")
    @ResponseBody
    public Object addAccident(Accident accident) {
        accident.setAddType(2);
        accidentService.insert(accident);
        return super.SUCCESS_TIP;
    }

    /**
     * 应急处置完成新增事故实例
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Accident accident) {

        //获取当前系统用户id
        Integer userId = ShiroKit.getUser().getId();
        //查询当前用户是否有正在应急处置的事故
        Alarm alarm = alarmMapper.selectByUserId(userId);
        if(alarm.getStationId()!=null){
            String stationIds =alarm.getStationId();
            List<Integer> stationIdList = new ArrayList(Arrays.asList(stationIds.split("/")));
            List<Roadnet> roadnetList = new ArrayList<>();
            String stationName = "";
            for(int i=0;i<stationIdList.size();i++){
                Roadnet station = roadnetMapper.selectById(stationIdList.get(i));
                roadnetList.add(station);
            }
            for(int i=0;i<roadnetList.size();i++){
                if(i==roadnetList.size()-1){
                    stationName += roadnetList.get(i).getName();
                }
                else{
                    stationName += roadnetList.get(i).getName()+">>";
                }
            }
           accident.setName(roadnetMapper.selectById(alarm.getLineId()).getName()+":"+stationName);
            accident.setAddType(1);
        }
        if(alarm!=null){
            alarm.setStep(4);
            accident.setLocale(alarm.getLocale());
            if (accidentService.insert(accident)) {
                alarm.setAccidentId(accident.getId());
                alarmMapper.updateById(alarm);
                return accident.getId();
            }
        }
        return super.SUCCESS_TIP;
    }

    /**
     * 删除事故实例
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") List<Integer> ids) {
        accidentService.deleteBatchIds(ids);
        return SUCCESS_TIP;
    }

    /**
     * 修改事故实例
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Accident accident) {
        accidentService.updateById(accident);
        return super.SUCCESS_TIP;
    }

    /**
     * 事故实例详情
     */
    @RequestMapping(value = "/detail/{accidentId}")
    @ResponseBody
    public Object detail(@PathVariable("accidentId") Integer accidentId) {
        return accidentService.selectById(accidentId);
    }

    /**
     * 跳转应急处置报告
     */
    @RequestMapping("/dispose_report/{accidentId}")
    public String resourceAdd(@PathVariable Integer accidentId, Model model) {
        Accident accident = accidentService.selectById(accidentId);
        Map<String, Object> accidentMap = BeanKit.beanToMap(accident);
        model.addAttribute("item", new AccidentWarpper(accidentMap).warp());
        LogObjectHolder.me().set(accident);
        return PREFIX + "dispose_report.html";
    }


    @RequestMapping(value = "/exportDocByT",headers = {"Accept=application/msword"})
    public String exportDocByT(HttpServletRequest request,
                               ModelMap modelMap, DisposeReport disposeReport) {
        Map map = BeanKit.beanToMap(disposeReport);
        map.put("principals", getPricipals());
        modelMap.put(TemplateWordConstants.FILE_NAME,"处置报告");
        modelMap.put(TemplateWordConstants.MAP_DATA,map);
        modelMap.put(TemplateWordConstants.URL,"export/template/report.docx");
        return TemplateWordConstants.EASYPOI_TEMPLATE_WORD_VIEW;
    }

    private List<Principal> getPricipals() {
        List<Principal> list = new ArrayList<>();
        String[] names = getParas("name");
        String[] duties = getParas("duty");
        String[] telphones = getParas("telphone");

        if (names == null || duties == null || telphones == null) {
            Principal principal = new Principal("", "", "");
            list.add(principal);
            return list;
        }

        int length = Math.min(Math.min(names.length, duties.length), telphones.length);

        for(int i = 0 ; i<length;i++) {
            Principal principal = new Principal(names[i], duties[i], telphones[i]);
            list.add(principal);
        }
        return list;

    }


}
